package org.jash.learnmvp.chat;

import android.os.Bundle;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.appbar.MaterialToolbar;
import com.hyphenate.EMMessageListener;
import com.hyphenate.EMValueCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMCursorResult;
import com.hyphenate.chat.EMFetchMessageOption;
import com.hyphenate.chat.EMMessage;


import org.jash.learnmvp.R;

import java.util.List;

public class ChatDetailActivity extends AppCompatActivity {
    private String username;
    private EditText content;
    private RecyclerView recycler;
    private MessageAdapter adapter;
    private MaterialToolbar toolbar;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat_detail);
        username = getIntent().getStringExtra("username");
        content = findViewById(R.id.content);
        toolbar = findViewById(R.id.toolbar);
        recycler = findViewById(R.id.recycler);
        adapter = new MessageAdapter();
        recycler.setAdapter(adapter);
//        recycler.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, true));
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        setTitle("与" + username + "聊天");
        findViewById(R.id.send).setOnClickListener(v -> {
            EMMessage message = EMMessage.createTextSendMessage(content.getText().toString(), username);
            EMClient.getInstance().chatManager().sendMessage(message);
            adapter.addAll(0, List.of(message));
        });
        EMClient.getInstance().chatManager().asyncFetchHistoryMessages(username, EMConversation.EMConversationType.Chat, 50, "", new EMFetchMessageOption(), new EMValueCallBack<EMCursorResult<EMMessage>>() {
            @Override
            public void onSuccess(EMCursorResult<EMMessage> emMessageEMCursorResult) {
                runOnUiThread(() -> adapter.addAll(emMessageEMCursorResult.getData()));
            }

            @Override
            public void onError(int i, String s) {
                runOnUiThread(() -> Toast.makeText(ChatDetailActivity.this, s, Toast.LENGTH_SHORT).show());
            }
        });
        EMClient.getInstance().chatManager().addMessageListener(new EMMessageListener() {
            @Override
            public void onMessageReceived(List<EMMessage> list) {
                adapter.addAll(0, list);
            }
        });
    }
}